package common

import (
	"io/ioutil"
	"os"
	"os/exec"
)

func EditString(str string) (string, error) {
	tempFile, err := ioutil.TempFile("", "vim-temp-")
	if err != nil {
		return "", err
	}
	defer os.Remove(tempFile.Name()) // delete temp file after edit

	tempFile.WriteString(str)
	tempFile.Close()

	cmd := exec.Command("vim", tempFile.Name())
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err = cmd.Run()
	if err != nil {
		return "", err
	}

	content, err := ioutil.ReadFile(tempFile.Name())
	if err != nil {
		return "", err
	}
	return string(content), nil
}
